// mouse.js
import { ref } from 'vue'
import { onReachBottom, onReady } from '@dcloudio/uni-app'

export const usePage = getPage => {
    // 页码,默认为1
    const page = ref(1)

    // 页大小,默认为10
    const limit = ref(10)

    // 关键字
    const keyword = ref('')

    // 类别
    const type = ref('')

    // 分类ID
    const sid = ref('')

    // 优惠券ID
    const couponId = ref('')

    // 是否新品,不为空的字符串即可
    const news = ref('')

    // 是否积分兑换商品
    const isIntegral = ref('')

    // 到底了
    const loadend = ref(false)

    // 加载中
    const loading = ref(false)

    // 是否有数据
    const listEmpty = ref(false)

    const dataList = ref([])

    const otherQuery = ref({})

    const handleGetDataList = async () => {
        if (loading.value || loadend.value) return

        loading.value = true
        const products = await getPage({
            page: page.value,
            limit: limit.value,
            keyword: keyword.value,
            type: type.value,
            sid: sid.value,
            couponId: couponId.value,
            news: news.value,
            isIntegral: isIntegral.value,
            ...otherQuery.value
        })
        listEmpty.value = false
        if (products) {
            const list = products.list && Array.isArray(products.list) ? products.list : products;
            if (Array.isArray(list)) {
                if (list.length <= 0) {
                    if (page.value === 1) {
                        listEmpty.value = true;
                    } else {
                        loadend.value = true;
                    }
                } else {
                    dataList.value = dataList.value.concat(list);
                }
            }
        }
        loading.value = false
    }

    const handleRefresh = async () => {
        loadend.value = false
        loading.value = false
        page.value = 1
        dataList.value = []
        console.log(dataList.value, '09820394803284032432')
        await handleGetDataList()
    }

    onReady(() => {
        // handleGetDataList()
    })

    onReachBottom(() => {
        if (loading.value || loadend.value) return
        page.value += 1
        handleGetDataList()
    })

    // 通过返回值暴露所管理的状态
    return {
        type,
        dataList,
        page,
        limit,
        keyword,
        loading,
        loadend,
        listEmpty,
        news,
        sid,
        couponId,
        refresh: handleRefresh,
        otherQuery
    }
}
